package com.gamesense.client.module.modules.exploits;

import com.gamesense.api.settings.Setting;
import com.gamesense.api.util.world.WorldUtils;
import com.gamesense.api.util.misc.MessageBus;
import com.gamesense.client.module.Module;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.Vec3d;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashMap;

public class CoordExploit extends Module{
	public CoordExploit(){super("CoordExploit", Category.Exploits);}

	private final HashMap knownPlayers = new HashMap();
	private final HashMap tpdPlayers = new HashMap();
	private int numTicks = 0;
	private int numForgetTicks = 0;

	Setting.Boolean chatMessages;

	public void setup(){
		chatMessages = registerBoolean("Chat Messages", "ChatMessages", false);
	}

	public void saveFile(String pos, String name){
		try{
			File file = new File("./GameSense/Misc/CoordExploit.json");
			file.getParentFile().mkdirs();
			PrintWriter writer = new PrintWriter(new FileWriter(file, true));
			writer.println("name: " + name + " coords: " + pos);
			writer.close();
		}
		catch (Exception e){
			MessageBus.sendClientPrefixMessage("Error saving file: " + e);
		}
	}

	public void onUpdate(){
		if (mc.player == null || mc.world == null){
			return;
		}

		if (numTicks >= 50){
			numTicks = 0;

			for (EntityPlayer entityPlayer : mc.world.playerEntities){
				if (entityPlayer == mc.player){
					return;
				}

				Vec3d playerPos = new Vec3d(entityPlayer.posX, entityPlayer.posY, entityPlayer.posZ);

				if (knownPlayers.containsKey(entityPlayer)){

					if (Math.abs(((Vec3d)knownPlayers.get(entityPlayer)).distanceTo(playerPos)) > 50.0D && Math.abs(mc.player.getPositionVector().distanceTo(playerPos)) > 100.0D && (!tpdPlayers.containsKey(entityPlayer.getName()) || tpdPlayers.get(entityPlayer.getName()) != playerPos)){
						if (chatMessages.getValue()){
							MessageBus.sendClientPrefixMessage("Player " + entityPlayer.getName() + " has teleported to " + WorldUtils.vectorToString(playerPos));
						}

						this.saveFile(WorldUtils.vectorToString(playerPos), entityPlayer.getName());
						knownPlayers.remove(entityPlayer);
						tpdPlayers.put(entityPlayer.getName(), playerPos);
					}

					knownPlayers.put(entityPlayer, playerPos);
				}
				else {
					knownPlayers.put(entityPlayer, playerPos);
				}
			}
		}

		if (this.numForgetTicks >= 9000000){
			tpdPlayers.clear();
		}
		numTicks++;
		numForgetTicks++;
	}
}